package com.company.笔试.合并有序链表;

import com.company.笔试.ListNode;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {

    public static void main(String[] args) {
        ListNode a = new ListNode(5);
        a.next = new ListNode(6);
        a.next.next = new ListNode(9);
        ListNode b = new ListNode(1);
        b.next = new ListNode(3);
        b.next.next = new ListNode(6);
        Solution solution = new Solution();
        ListNode res = solution.solution(a, b);
        while (res!=null){
            System.out.println(res.val);
            res = res.next;
        }
    }



    /**
     * 链表合并  {5,6,9},{1,3,6}
     * @param a ListNode类 链表A
     * @param b ListNode类 链表B
     * @return ListNode类
     */
    public ListNode solution (ListNode a, ListNode b) {
        // write code here
        ListNode cc ;
        if (a.val<b.val){
            cc = a; //
        }else {
            cc=b;   // 1
        }
        ListNode c = cc;
        boolean flag = true;
        while (a!=null&&b!=null){
            if (a.val>b.val){ //5>1
               ListNode tmp = b;
               b = b.next;
               if (flag) {
                   flag =false;
                   continue;
               }
               c.next= tmp;
               c=c.next;
            }else if (a.val <=b.val){
                if (a.val==b.val){
                    a = a.next;
                    continue;
                }
                ListNode tmp = a;
                a = a.next;
                if (flag) {
                    flag =false;
                    continue;
                }

                c.next= tmp;
                c=c.next;
            }
        }
        if (a!=null){
            c.next = a;
        }
        if (b!=null){
            c.next = b;
        }
        return cc;
    }
}